#include "SaveImgTask.h"

SaveImgTask::SaveImgTask(char* body, int client_fd, int len, int shmid, int msgid) :BaseTask(body, client_fd, len, shmid, msgid)
{
}

void SaveImgTask::working()
{
	IMGUPLOAD_REQ req = { 0 };
	//拷贝分析数据
	memcpy(&req, body, sizeof(IMGUPLOAD_REQ));
	Img img = req.img;
	cout << "------------------------操作日志------------------" << endl;
	// 获取当前时间点（系统时钟）
	auto now = std::chrono::system_clock::now();
	auto in_time_t = std::chrono::system_clock::to_time_t(now);
	std::stringstream ss;
	ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");

	cout << "时间: " << ss.str();  // ctime自带换行
	cout << "功能：上传图片" << endl;
	cout << "类型：接收" << endl;
	cout << "用户：" << req.user_id << endl;
	cout << "接收数据包：" << endl;
	cout << "图片名:" << img.img_name << "\n"
		<< "图片类型:" << img.img_type << "\n"
		<< "图片地址:" << img.img_path << endl;

	//保存图片

	send(Success, "上传图片：上传成功！", req.user_id);

}

void SaveImgTask::send(int statu, string message, int user_id)
{
	ShmControl* shm = (ShmControl*)shmat(shmid, NULL, 0);
	int index = -1;//空闲下标
	// 寻找下一个空闲块（状态0）
	for (int i = 0; i < MEMORYNUMBER; i++) {
		int status = shm->blocks[i].status;
		if (status == 0) { // 空闲
			index = i;
			break;
		}
	}
	HEAD head = { 0 };
	RESP resp = { 0 };//响应
	char send[MEMORYSIZE] = { 0 };
	strcpy(resp.message, message.c_str());
	resp.status_code = statu;
	//写头
	head.service_type = IMGUPLOAD;
	head.checksum = 100;
	head.data_len = sizeof(RESP);
	//头体结合
	memcpy(send, &head, sizeof(HEAD));
	memcpy(send + sizeof(HEAD), &resp,sizeof(RESP));
	//写入共享内存
	sem_p(sem_shm, 0);//获取共享内存锁
	ShmBlock* block = &shm->blocks[index];
	memcpy(block->data, send, sizeof(block->data));//考入共享内存
	block->status = 1;                   // 标记为已写
	shmdt(shm);
	sem_v(sem_shm, 0);//释放共享内存锁
	//写入消息队列
	MSG msg = { 0 };
	msg.client_fd = client_fd;
	msg.index = index;
	msg.mtype = 1;
	msgsnd(msgid, &msg, sizeof(MSG), 0);
	cout << "------------------------操作日志------------------" << endl;
	// 获取当前时间点（系统时钟）
	auto now = std::chrono::system_clock::now();
	auto in_time_t = std::chrono::system_clock::to_time_t(now);
	std::stringstream ss;
	ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");

	cout << "时间: " << ss.str() << "\n"   // ctime自带换行
		<< "功能：上传图片\n"
		<< "类型：发送\n"
		<< "用户id：" << user_id << "\n"
		<< "发送数据包：" << "\n"
		<< "状态:" << statu << "\n"
		<< "信息:" << message << endl;
}
